window.onload = function(){
    var container = document.querySelector("#container");
    var canvas = document.createElement("canvas");
    canvas.width = container.clientWidth;
    canvas.height = container.clientHeight;
    container.appendChild(canvas);

    window.onresize = function(){
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
    };

    var gl = canvas.getContext("webgl");

    var VERTEX_SHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'attribute vec4 a_Color;\n' +
    'varying vec4 v_Color;\n' +
    'void main(){\n' +
    'gl_Position = a_Position;\n' +
    'gl_PointSize = 10.0;\n' +
    'v_Color = a_Color;\n' +
    '}\n';

    var FRAGMENT_SHADER_SOURCE =
    'precision mediump float;\n' + // float变量没有默认精度，所以使用前必须声明，否则会出错
    'varying vec4 v_Color;\n' +
    'void main(){\n' +
    'gl_FragColor = v_Color;\n' +
    '}';


    // 1.1创建着色器对象
    var vertex_shader_object = gl.createShader(gl.VERTEX_SHADER);
    var fragment_shader_object = gl.createShader(gl.FRAGMENT_SHADER);
    
    // 1.2装载着色器资源
    gl.shaderSource(vertex_shader_object, VERTEX_SHADER_SOURCE);
    gl.shaderSource(fragment_shader_object, FRAGMENT_SHADER_SOURCE);
    
    // 1.3编译着色器
    gl.compileShader(vertex_shader_object);
    gl.compileShader(fragment_shader_object);

    // 2.1创建程序
    var program = gl.createProgram();
    
    // 2.2.附着着色器对象到program
    gl.attachShader(program, vertex_shader_object);
    gl.attachShader(program, fragment_shader_object);
    
    // 2.3.链接program
    gl.linkProgram(program);
    
    // 2.4.使用program
    gl.useProgram(program);

    var vertices_Positions_Colors = new Float32Array([
        0.0,    0.5,    1.0,    0.0,    0.0,
        -0.5,   -0.5,   0.0,    1.0,    1.0,
        0.5,    -0.5,   0.0,    0.0,    1.0,
    ]);

    var a_Position = gl.getAttribLocation(program, "a_Position");
    var a_Color = gl.getAttribLocation(program, "a_Color");
    var fsize = vertices_Positions_Colors.BYTES_PER_ELEMENT;

    // 处理位置
    var vertex_Positon_Buffer = gl.createBuffer(gl.ARRAY_BUFFER);
    gl.bindBuffer(gl.ARRAY_BUFFER,vertex_Positon_Buffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices_Positions_Colors, gl.STATIC_DRAW);
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT,false, fsize*5, 0);
    gl.enableVertexAttribArray(a_Position);

    // 处理颜色
    var vertex_Color_Buffer = gl.createBuffer(gl.ARRAY_BUFFER);
    gl.bindBuffer(gl.ARRAY_BUFFER, vertex_Color_Buffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices_Positions_Colors, gl.STATIC_DRAW);
    gl.vertexAttribPointer(a_Color, 3,gl.FLOAT,false,fsize*5,fsize*2);
    gl.enableVertexAttribArray(a_Color);

    gl.clearColor(0.0,0.0,0.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.POINTS, 0, 3);
}